import { _decorator, Component, Node, Collider, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CollisionEvent')
export class CollisionEvent extends Component {

    @property(Node) player: Node

    progress: number = 0
    flag: boolean = false
    injury: number = 0.001

    start() {
        let collider = this.player.getComponent(Collider);
        // 监听触发事件
        collider.on('onCollisionEnter', this.onCollisionEnter, this);
        collider.on('onCollisionStay', this.onCollisionStay, this);
        collider.on('onCollisionExit', this.onCollisionExit, this);
    }

    update(deltaTime: number) {
        this.progressUpdate()
    }

    onCollisionEnter(e) {
        // console.log('onCollisionEnter', e);
    }

    onCollisionStay(e) {
        // console.log('onCollisionStay', e, e.otherCollider.node.parent.parent.name);
        if (e.otherCollider.node.parent.parent.name == '地形') {
            this.injury = 0.01
        } else if (e.otherCollider.node.parent.parent.name == '敌人') {
            const node: Node = e.otherCollider.node.parent.parent
            const playerScale = this.player.getScale().x
            const nodeScale = this.node.getScale().x
            if (node.getScale().x > this.player.getScale().x) {
                this.injury = 0.5
                const playerResScale = playerScale - nodeScale / 8
                this.player.setScale(playerResScale, playerResScale, playerResScale)
            } else {
                this.injury = -0.01
                const playerResScale = playerScale + nodeScale / 10
                this.player.setScale(playerResScale, playerResScale, playerResScale)
                this.destroy()
            }
        } else {
            this.injury = 0.001
        }
        this.player.children[0].children[0].active = true
        this.player.children[0].children[1].active = false
        this.flag = true
    }

    onCollisionExit(e) {
        // console.log('onCollisionExit', e);
        this.player.children[0].children[0].active = false
        this.player.children[0].children[1].active = true
        this.flag = false
    }

    progressUpdate() {
        if (this.flag) {
            this.progress += this.injury
            this.progress = this.progress > 1 ? 1 : this.progress
        } else {
            this.progress -= 0.00005
            this.progress = this.progress < 0 ? 0 : this.progress
        }

        // 修改界面 
        const radio = 1 - this.progress
        let value = Math.floor(radio * 100)
        this.node.children[0].children[1].children[0].getComponent(Label).string = `${value} / 100`
        this.node.children[2].setScale(1 - this.progress, 1, 1)

        if (this.progress == 1) {
            console.log('game over');

        }
    }

}


